<?php

namespace apps\api\modules\site\controllers;

use common\modules\site\logic\SmsLogic;
use Yii;
use apps\api\modules\ApiBaseController;
use common\modules\user\User;
use xing\helper\exception\LanguageException;
use xing\helper\text\CheckHelper;

class SiteController extends ApiBaseController
{
    public $checkLogin = false;

    public function actionPhpInfo()
    {
        if (Yii::$app->request->get('cx') != '1qjh') throw new \Exception('用户cx密码不对');
        echo phpinfo();
        exit();
    }

    /**
     * 获取手机验证码
     * @return array
     * @throws \Exception
     */
    public function actionGetMobileCode()
    {
        $mobile = Yii::$app->request->post('mobile');
        $repeatCheck = Yii::$app->request->post('repeatCheck');
        $registerCheck = Yii::$app->request->post('registerCheck');
        try {

            CheckHelper::checkMobile($mobile);
            if ($repeatCheck || $registerCheck) {
                $hasMobile = User::existsMobile($mobile);
                // 已被注册的不发送
                if ($repeatCheck && $hasMobile) throw new \Exception('手机已被注册');
                // 未注册的不发送
                if ($registerCheck && !$hasMobile) throw new \Exception('手机未注册');
            }
            SmsLogic::sendTextCode($mobile);
            return $this->returnApiSuccess();
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }



    /**
     * 检查手机验证码是否正确
     * @return array
     */
    public function actionCheckMobileCode()
    {
        $mobile = Yii::$app->request->post('mobile');
        $code = Yii::$app->request->post('code');
        try {

            // 检查验证码
            $sms = SmsLogic::getInstance()->setMobile($mobile);
            if (!CheckHelper::checkMobile($mobile)) throw new LanguageException('手机号码错误');
            if (empty($code) || !$sms->checkCode($code)) throw new LanguageException('验证码错误');

            return $this->returnApiSuccess();
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }
}
